$('.foot').load("tpl/footer.html");
$(function() {
    //***获取系统当前时间***
    setInterval(function () {
        var date = new Date();
        var d = date.toLocaleDateString();
        d = d.replace("/", "-").replace("/", "-");
        var t = date.toTimeString();
        t = t.slice(0, date.toTimeString().indexOf(" "));
        $('.date').html(d + " " + t);
    }, 1000)
});
angular.module('sinagp',[]).controller('parentCtr',function($scope) {
    $scope.jump = function(routPath){
        $.mobile.changePage(routPath,{transition:''});
        location.reload();
    };
    //$(document).on('pagecreate', function (event) {
    //    //获取要加载到的容器
    //    var page = event.target;
    //    //获取作用域对象
    //    var scope = $(page).scope();
    //    //获取注入器对象
    //    var injector = $(page).injector();
    //    //调用注入器，为程序提供$compile服务
    //    injector.invoke(function($compile){
    //        //编译并链接DOM节点
    //        $compile(page)(scope);
    //        scope.$digest();
    //    });
    //})

    //股票查询
    $('[data-role="header"] a[data-icon="search"]').click(function(){
        $scope.jump("#gpSelect");
    });
    //返回页面并刷新
    $('[data-role="header"] a[data-icon="back"]').click(function(){
        location.reload();
    });
    $('[data-role="footer"]').on('click','ul li>a',function(){
        location.reload();
    });
    $('[data-role="header"] a[data-icon="home"]').on('click','ul li>a',function(){
        $scope.jump("#optionalStock");
    });
    //跳转股票详情函数
    $scope.detail=function(e_elem,on_elem,obj){
        $(e_elem).on('click',on_elem,function(){
            $scope.jump('#detail');
            //保存当前股票代码
            var gid=$(this).find(obj).html();
            if(gid[0]=="6"){
                gid="sh"+gid;
            }else if(gid[0]=="0"){
                gid="sz"+gid;
            }
            sessionStorage.setItem('gid',gid);
        });
    };
    //买、卖时检测登录状态，并跳转指定页面
    $scope.isLogin=function(obj){
        var id=sessionStorage.getItem('uid');
        if(!id){
            $scope.jump('#login');
        }else{
            $scope.jump(obj);
        }
    };

}).controller('homeCtr',function($scope,$http,$rootScope){
    $http.get("data/select-dapan.php?gid=sh000001").success(function(data){
        $scope.shData=data.result[0].data;
        if($scope.shData.gid){
            $scope.hasGid=true;
        }
    });
    $http.get("data/select-dapan.php?gid=sz399001").success(function(data){
        $scope.szData=data.result[0].data;
    });
    //获取localStorage自选股id,并访问服务器查询股票详情
    var idlist=JSON.parse(localStorage.getItem('idlist'));
    if(idlist){
        var zixuan=[];
        for(var i=0;i<idlist.length;i++){
            var gid=idlist[i].gid;
            $http.get("data/select-dapan.php?gid="+gid).success(function(data){
                var zi=data.result[0].data;
                zixuan.push(zi);
            });
        }
        $scope.zixuan=zixuan;
        $rootScope.zixuan=zixuan;
    }
    $scope.detail('#mygpLists','tr','p');
    $scope.detail('#dapan','div','h4 span');
}).controller('mainCtr',function($scope,$http,$rootScope){
    //页面加载，获取前20个股票列表
    $http.get("data/select-sh.php").success(function(data){
        $scope.data=data.result.data;
        $scope.gpData=$scope.data;
        $rootScope.page=2;//更多加载从第2页开始
    });
    $scope.col = 'code';//默认按name列排序
    $scope.desc = 0;//默认排序条件升序
    //是否还有更多数据可供加载
    $scope.hasMore = true;
    $scope.loadMore = function(url){
            $scope.page=$rootScope.page;
            $http.get(url+$scope.page).success(function(data){
                $scope.data=data.result.data;
                //判断服务器返回的数量不足20条
                if($scope.data.length<20){
                    $scope.hasMore = false;
                }
                $scope.gpData = $scope.gpData.concat($scope.data);
                $rootScope.page=$scope.page+1;
            });
        };
    function ghLists(url){
            $http.get(url+"1").success(function(data){
                $scope.data=data.result.data;
                $scope.gpData = $scope.data;
                //判断服务器返回的数量不足20条
                if($scope.data.length<20){
                    $scope.hasMore = false;
                }
            });
            $rootScope.page=2;
        }
    $('#lists').on('click','a',function(){
            var gs=$(this).attr('i');
            if(gs=="sh"){
                ghLists("data/select-sh.php?page=");
                $('.sh').show();
                $('.sz').hide();
            }else if(gs=="sz"){
                ghLists("data/select-sz.php?page=");
                $('.sh').hide();
                $('.sz').show();
            }
        });
    //跳转到股票详情面
    $scope.detail('#gpLists tbody','tr','p');
}).controller('detailCtr',function($scope,$http,$rootScope){
	//获取股票详情数据
    var gid=sessionStorage.getItem('gid');
    if(gid){
        $http.get("data/select-dapan.php?gid="+gid).success(function(data) {
            var data = data.result[0];
            $scope.data=data.data;
            $scope.gopicture=data.gopicture;//数据图表
        });
		var idlist=JSON.parse(localStorage.getItem('idlist'));
        if(idlist){
			for(var i=0;i<idlist.length;i++){
				var id=idlist[i].gid;
				if(id==gid){
					$('#mygp').html("删自选");
				};
			}
		}
    };
    $('#mygp').click(function(){
        var html=$(this).html();
        if(html=="加自选"){
			//将当前股票数据保存于session中，减少请求次数
			var idlist=JSON.parse(localStorage.getItem('idlist'));
            if(idlist){
				var newlist=[];
				for(var i=0;i<idlist.length;i++){
					newlist.push(idlist[i]);
				}
                var id={'gid':gid};
                newlist.push(id);
                localStorage.setItem('idlist',JSON.stringify(newlist));
            }else{
                var list=[];
                var id={'gid':gid};
                list.push(id);
                localStorage.setItem('idlist',JSON.stringify(list));
            }
            $(this).html("删自选");
        }else{
			var idlist=localStorage.getItem('idlist');
			idlist=JSON.parse(idlist);
			for(var i=0;i<idlist.length;i++){
				var id=idlist[i].gid;
				if(id==gid){
					idlist.splice(i,1);
				};
			}
            localStorage.setItem('idlist',JSON.stringify(idlist));
            $(this).html("加自选");
			$scope.jump('#optionalStock');
        }
    });
    //买入
    $scope.buy=function(){
        $scope.isLogin('#entrust');
    };
    //卖出
    $scope.sell=function(){
        $scope.isLogin('#entrust');
    };
    //撒单
    $scope.recall=function(){
        $scope.isLogin('#entrust');
    }
}).controller('gpselCtr',function($scope,$http){
    $scope.hasHistory=false;
    //页面加载查询历史记录
    var history=localStorage.getItem('history');
    if(history!=null){
        history=JSON.parse(history);
        $scope.history=history;
        $scope.hasHistory=true;
    }
    $scope.hasData=false;//判断是否隐藏数据列表
    $scope.$watch('kw', function(){
        var kw=$scope.kw;
        if( kw ){
            if(kw[0]=="0"){
                kw="sz"+kw;
            }else if(kw[0]=="6"){
                kw="sh"+kw;
            }
            if(kw.length=="8"){
                $http.get('data/select-dapan.php?gid='+kw).success(function(data){
                    $scope._data = data.result[0];
                    $scope.data=$scope._data.data;
                    $scope.gopicture=$scope._data.gopicture;
                    if($scope.data){//判断是否隐藏数据列表
                        $scope.hasData=true;
                    }
                    var his=localStorage.getItem('history');
                    var arr=[];
                    arr.push($scope.data);
                    //localStorage中的对象数组打散，重新添加到arr中，并将当前股票数据压入arr中，形成新的数组
                    if(his!=null){
                        his=JSON.parse(his);
                        for(var i=0;i<his.length;i++){
                            arr.push(his[i]);
                        };
                        localStorage.setItem('history',JSON.stringify(arr));
                    }else{
                        localStorage.setItem('history',JSON.stringify(arr));
                    }
                })
            }
        }
    });
    $scope.showDetail=function(gid){
        //保存gid到session中
        sessionStorage.setItem('gid',gid);
        //跳转到股票详情面
        $scope.jump('#detail');
    }
    //清除历史记录
    $scope.delAll=function(){
        $scope.history.length=0;
    }
}).controller('tradeCtr',function($scope,$http){
    $scope.buying=function(){
        $scope.isLogin("#entrust");
    }
}).controller('userCtr',function($scope,$http){

}).controller('loginCtr',function($scope,$http){
    $scope.hasname=true;//判断显示哪个提示语
	//判断是否本地储存了账户信息
	var phone=localStorage.getItem('uphone');
	$('#password').val('');
	if(phone){
		$('#text-basic').val(phone);
	}else{
		$('#text-basic').val('');
	}
    //账号登录
    $scope.login=function(){
        var phone=$('#text-basic').val();
        var pwd=$('#password').val();
        $http.get('data/user_login.php?phone='+phone+'&pwd='+pwd).success(function(data){
            if(data.length==0||data=="[]"){
                //不存在用户
                $scope.hasname=false;
            }else{
                var uid=data[0].uid;
                sessionStorage.setItem('uid',uid);
                //判断是否记住用户名
                var check=$('#slider2').val();
                var uphone=data[0].uphone;
                if(check=="on"){
                    localStorage.setItem('uphone',uphone);
                }else if(check=="off"){
                    localStorage.removeItem('uphone');
                }
                //判断是否交易超时
                var outTime=$('#tradeOvertime').val();
                function calc(){
                    outTime--;
                    if(outTime==0){
                        sessionStorage.removeItem('uid');
                        $scope.jump('#login');
                    }
                }
                setInterval(calc,60000);//每分钟执行一次
				sessionStorage.setItem('account',JSON.stringify(data[0]));
                window.history.go(-1);
            }
        });
    };
    //跳转到注册页面
    $scope.goRegi=function (){
        $('#loging').hide();
        $('#register').show();
	    $('#uname,#phone,#upwd,#ucode').val('');
    };
    //获取验证码
    $scope.getCode=function(){
        var zimu=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
        var num=[0,1,2,3,4,5,6,7,8,9];
        var z=Math.floor(Math.random()*26);
        var n=Math.floor(Math.random()*10);
        var x=(z*n+10)%3;
        var code=zimu[z]+n*n+zimu[x]+x*n+8;
        $('#ucode').val(code);
    };
    //验证手机号是否存在
    $scope.$watch('phone', function() {
        var p=$scope.phone;
        var reg=/^1[3,5,7,8]{1}[0-9]{9}$/;
        if(reg.test(p)){
            $.post('data/user_phone.php',{'uphone':p},function(data){
                if(data.length>0){
                    $('#error').show().html("该手机号码已注册");
                    $('#user-alt').hide();
				}else{
                    $('#error').show().html("手机号码可用");
                    $('#user-alt').hide();
				}
            });
        }
    });
    //提交注册
    $scope.register=function(){
        var n=$('#uname').val();
        var p=$('#phone').val();
        var w=$('#upwd').val();
        var c=$('#ucode').val();
        if(n==""||p==""||w==""||c==""){
            $('#phone').focus();
        }else if( p.length==11){
            $http.get("data/user_register.php?uname="+n+"&uphone="+p+"&upwd="+w+"&ucode="+c).success(function(data){
                if(data.id){
                    $scope.jump("#detail");
                    sessionStorage.setItem('uid',data.id);
                }else if(data.err){
                    alert("注册失败，该手机号已存在");
                    $('#phone').focus();
                }else{
                    alert("未知错误，请重试");
                }
            });
        }else{
            $('#phone').focus();
        }
    }
}).controller('entrustCtr',function($scope,$http,$rootScope){
    var gid=sessionStorage.getItem('gid');
    var uid=sessionStorage.getItem('uid');
    //自选股数据
    $scope.zixuan=$rootScope.zixuan;
    $('#gpmi').on('click','.abc',function(){
        var kw=$(this).find('p').html();
        watch(kw);
    });
    //持仓数据.有问题，成本价等被覆盖
    function chicang(){
        $http.get('data/kucun.php?uid='+uid).success(function(data){
            if(data.length==0){
                $('#gpkuqun tbody').empty().append(
                    '<tr><td colspan="4">没有持仓股票</td></tr>'
                );
            }else{
                var arr=[];
                for(var i=0;i<data.length;i++){
                    var d= JSON.parse(data[i].data);
                    $http.get('data/select-dapan.php?gid='+d.gid).success(function(data){
                        d.nowPri=data.result[0].data.nowPri;
                    });
                    arr.push(d);
                }
                $scope.kucun=arr;
                console.log(arr);
            }
        });
    }
    chicang();
	/****计算最多可以买多少股******/
	var Account=JSON.parse(sessionStorage.getItem('account'));
	function maxCount(){
		var nowPri=$('#gpri').val();
        var canbuy=Account.remainingSum;
        canbuy=""+Math.floor(canbuy/nowPri);
        var shi=canbuy.slice(canbuy.length-2);
        canbuy=canbuy-shi;
        if(canbuy<=0){
            canbuy=0;
        }
        $('#canbuy').html(canbuy+" 股");
    };
    //点击清空代码输入框的内容
    $('input[name="daima"]').click(function(){
        $(this).val('');
        $('input[name="price"]').val('');
        $('input[name="count"]').val('');
    });
    //查询股票详情
    if(gid){
        function getGp(gid){
            $http.get('data/select-dapan.php?gid=' + gid).success(function(data){
                $scope._data = data.result[0];
                $scope.data = $scope._data.data;
                //重写代码框的value值
                $('input[name="daima"]').val(gid.slice(2)+" "+$scope.data.name);
                //自动输入价格
                var pri=parseFloat($scope.data.nowPri);
                $('input[name="price"]').val(pri.toFixed(2));
                sessionStorage.setItem('gid',gid);
				maxCount();
            });
        };
        getGp(gid);
    }
    //监听股票代码查询
    function watch(kw){
        if( kw ) {
            if (kw[0] == "0") {
                kw = "sz" + kw;
            } else if (kw[0] == "6") {
                kw = "sh" + kw;
            }
            if (kw.length == "8") {
                getGp(kw);
            }
        }
    };
    $scope.$watch('daima',function(){
        var kw=$scope.daima;
        watch(kw);
    });
    /*****选择可购买数量*******/
    function getBuy(num){
        var canbuy=parseFloat($('#canbuy').html());
        var buy=""+Math.floor(canbuy/num);
        var shi=buy.slice(buy.length-2);
        var bai=buy-shi;
        if(bai>=100){
            $('input[name="count"]').val(bai);
        }else{
            $('input[name="count"]').val(canbuy);
            return;
        }
    }
    //全部
    $scope.allin=function(){
        var canbuy=parseFloat($('#canbuy').html());
        $('input[name="count"]').val(canbuy);
    };
    // 1/2
    $scope.yibanin=function(){ getBuy(2)};
    // 1/3
    $scope.sanin=function(){ getBuy(3)};
    // 1/4
    $scope.siin=function(){ getBuy(4)};
    //购买股票
    $scope.theBuy=function(){
        if(uid){
            var pri=$('input[name="price"]').val();
            var count=$('input[name="count"]').val();
            if(count==0||count==""){
                alert("请输入数量");
                return;
            }
            var total=pri*count;
            total=total.toFixed(2);
            alert("确定买入："+count+"股，单价为:"+pri+",市值为："+total+"元");
            var name=$scope.data.name;
            var data={'name':name,'gid':gid,'pri':pri,'count':count,'total':total};
            data=JSON.stringify(data);
            $http.get('data/addKucun.php?uid='+uid+'&data='+data).success(function(data){
                if(data){
                    //更新持仓股票数据
                    chicang();
                }
            });
            var account=Account;//账户信息
            var marketValue=parseFloat(account.marketValue)+parseFloat(total);//持有市值
            var remainingSum=parseFloat(account.remainingSum)-parseFloat(total); //可用余额
            var yingkiu=parseFloat(account.yingkiu)+(($scope.data.nowPri-pri)*count);//盈亏
            var capitalAll=parseFloat(account.capitalAll)+(($scope.data.nowPri-pri)*count); //总资产
            $http.get("data/updataUser.php?uid="+uid+"&capitalAll="+capitalAll+"&remainingSum="+remainingSum+"&marketValue="+marketValue+"&yingkiu="+yingkiu).success(function(data){
                if(data){
                    //更新账户信息，并保存在localStorage中
                    account.capitalAll=capitalAll;
                    account.marketValue=marketValue;
                    account.remainingSum=remainingSum;
                    account.yingkiu=yingkiu;
                    sessionStorage.setItem('account',JSON.stringify(account));
                    //重新计算可购买数量
                    maxCount();
                }
            });
        }else{
            $scope.jump("#login");
        }
    };
});